//
//  ZMEditeAddressVC.swift
//  zhonglibang
//
//  Created by Rowling on 2021/1/8.
//

import UIKit
import RxSwift
class ZMEditeAddressVC: ZMViewController {
    enum EditeType {
        /// 新增收货地址
        case newAddress
        /// 编辑收货地址
        case editeAddress
        /// 兑奖地址
        case prizeAddress
    }
    
    var city = ""
    
    var province = ""
    
    var district = ""
    
    var addressMaxLength = 40
    
    @IBOutlet weak var nameText: UITextField!
    
    @IBOutlet weak var phoneText: UITextField!
    
    @IBOutlet weak var areaText: UITextField!
        
    @IBOutlet weak var defaultSwitch: UISwitch!
    
    @IBOutlet weak var deleteButton: UIButton!
    
    @IBOutlet weak var textView: ZMTextView!
    
    @IBOutlet weak var defauleView: UIView!
    
    @IBOutlet weak var okButton: UIButton!
    
    public var type : EditeType = .newAddress
    
    public var address : AddressModel?
    /// 保存成功回调
    public var successBlock : ((_ address: String)->())?
    
    var cityCode = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        bindVerify()
        fillOldData()
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
//        self.okButton.style.GradientLayerFit()
    }
    
    func bindVerify() {
        let userName = nameText.rx.text.orEmpty.map({$0.count > 0})
        let phone = phoneText.rx.text.orEmpty.map({$0.zm.isPhoneNum()})
        let area = areaText.rx.text.orEmpty.map({$0.count > 0})
        let detail = textView.rx.text.orEmpty.map({$0.count > 0})
        let allOk = Observable.combineLatest(userName, phone, area, detail).map { (a,b,c,d) -> Bool in
            return a && b && c && d
        }
        allOk.bind(to: okButton.rx.isEnabled).disposed(by: disposeBag)
        allOk.subscribe(onNext:{ [unowned self] resp in
            if resp {
                self.okButton.style.DefaultGradientLayer()
            }
            else {
                self.okButton.style.DisableGradientLayer()
            }
        }).disposed(by: disposeBag)
    }
    
    private func setUI() {
        switch type {
        case .newAddress:
            title = "新建收货地址"
        case .editeAddress:
            title = "编辑收货地址"
        case .prizeAddress:
            title = "兑奖地址"
            defauleView.isHidden = true
        }
        textView.textContainer.lineFragmentPadding = 0
        textView.textContainerInset = UIEdgeInsets.zero
        
        areaText.delegate = self
        // 隐藏删除按钮
        deleteButton.isHidden = (type != .editeAddress)
        
        phoneText.delegate = InputMananger.shard.onlyNumber
        /// 限制100
        textView.rx.text.orEmpty.subscribe(onNext:{ [unowned self] text in
            if text.count > addressMaxLength {
                self.textView.text = text.zm.substring(to: addressMaxLength)
            }
        }).disposed(by: disposeBag)
        
        okButton.setTitle(type == .newAddress ? "保存" : "保存", for: .normal)
        
        deleteButton.setTitleColor(Style.mainColor, for: .normal)
    }
    
    // 填充旧数据
    func fillOldData(){
        guard let address = address else {return}
        self.province = address.province
        self.city = address.city
        self.district = address.district
        self.nameText.text = address.realName
        self.areaText.text = address.province + " " + address.city + " " + address.district
        self.phoneText.text = address.phone
        self.textView.text = address.detail
        self.defaultSwitch.isOn = address.isDefault
        self.cityCode = address.cityId
        
        self.nameText.sendActions(for: .editingChanged)
        self.areaText.sendActions(for: .editingChanged)
        self.phoneText.sendActions(for: .editingChanged)
//        self.textView.

    }
    
    /// 删除
    @IBAction func deleteClick(_ sender: Any) {
        delete()
    }
    
    /// 确定
    @IBAction func okClick(_ sender: Any) {
        if nameText.text!.zm.noWhitespace() == "" {
            ZMToast.showToast(title: "请填写姓名")
            return
        }
        if phoneText.text!.zm.noWhitespace() == "" {
            ZMToast.showToast(title: "请填写电话")
            return
        }
        if phoneText.text!.zm.isPhoneNum() == false {
            ZMToast.showToast(title: "电话号码格式不正确")
            return
        }
        if areaText.text!.zm.noWhitespace() == "" {
            ZMToast.showToast(title: "请选择区域")
            return
        }
        if textView.text!.zm.noWhitespace() == "" {
            ZMToast.showToast(title: "请填写详细地址")
            return
        }
        if type == .prizeAddress {
            if let successBlock = successBlock {
                successBlock("\(areaText.text!)\(textView.text!)")
            }
            self.navigationController?.popViewController(animated: true)
        } else {
            save()
        }
    }
    
    //MARK:--------------------请求--------------------
    func save() {
        var pa = ["address" : ["city" : self.city, "cityId" : self.cityCode, "district" : self.district, "province" : self.province],
                  "detail": textView.text!,
                  "isDefault" : defaultSwitch.isOn,
                  "phone" : phoneText.text!,
                  "realName" : nameText.text!
        ] as [String : Any]
        if let addressId = address?.id {
            pa["id"] = addressId
        }
        ZMToast.showActivity()
        ZMAPIManage<AddressModel>.rxSendRequest(MineAPI.saveAddress(pa)).subscribe(onNext:{ [unowned self]resp in
            if resp.code == .success {
                ZMToast.hiddenActivity()
                if let successBlock = successBlock {
                    successBlock("")
                }
                if let ad = self.address {
                    ad.realName = self.nameText.text!
                    ad.detail = self.textView.text!
                    ad.city = self.city
                    ad.district = self.district
                    ad.province = self.province
                    ad.phone = self.phoneText.text!
                    ad.isDefault = self.defaultSwitch.isOn
                    ZMNotification.shard.subject.onNext(.addressEdite(ad))
                }
                self.navigationController?.popViewController(animated: true)
            }
        }).disposed(by: disposeBag)
    }
    
    func delete() {
        guard let id = address?.id else {
            ZMToast.showToast(title: "没有id")
            return
        }
        ZMToast.showActivity()
        ZMAPIManage<Any>.rxSendRequest(MineAPI.deleteAddress(["id" : "\(id)"])).subscribe(onNext:{ [unowned self] resp in
            if resp.code == .success {
                ZMToast.hiddenActivity()
                self.navigationController?.popViewController(animated: true)
                if let successBlock = successBlock {
                    successBlock("")
                }
            }
        }).disposed(by: disposeBag)
    }
}

extension ZMEditeAddressVC: UITextFieldDelegate {
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        if textField == areaText {
            view.endEditing(true)
            ZMProvinceCityView.show { [unowned self] (p, c, a) in
                areaText.text = "\(p.name) \(c.name) \(a?.name ?? "")"
                self.province = p.name
                self.city = c.name
                self.district = a?.name ?? ""
                self.cityCode = a?.cityId ?? c.cityId //a?.code ?? c.code
                textField.sendActions(for: .editingChanged)
            }
            return false
        }
        return false
    }
}
